class PositionCertificateStandard < ActiveRecord::Base
  extend PositionCertificateStandardRepository
  
  has_many   :position_certificate_assignments
  has_many   :certificates, through: :position_certificate_assignments
  composed_of :requre_certificate_organ, class_name: 'RequireCertificateOrgan', mapping: %w(requre_certificate_organ name),
              constructor: Proc.new { |requre_certificate_organ| RequireCertificateOrgan.find_by_name(requre_certificate_organ) }
  
  validates :position_id, :uniqueness => {:scope => :requre_certificate_organ}

  def add_certificate certificate
    unless certificates.include? certificate 
      certificates << certificate
    else
      errors.add(:certificate_id, '证书已经存在')
    end
  end

  def update_certificates certificate_ids
    old_certificate_ids = position_certificate_assignments.map(&:certificate_id)
    remove_certificate_ids = old_certificate_ids - certificate_ids
    add_certificate_ids = certificate_ids - old_certificate_ids

    position_certificate_assignments.where(certificate_id: remove_certificate_ids).map { |e| e.delete }

    add_certificate_ids.each do |certificate_id|
      add_certificate Certificate.find_by_id(certificate_id)
    end

  end

end
